<?php

namespace app\admin\controller;
use app\common\model\Account;
use app\common\model\ShopMember;
use app\common\model\ShopMemberCard;
use app\common\model\ShopSchoolRegion;
use app\common\model\ShopStore;
use app\common\model\User;
use app\common\service\Status;
use buildView\Button;
use buildView\Form;
use buildView\Grid;
use library\tools\Data;
use think\Controller;
use think\Db;
use think\Request;
use app\common\facade\Token;
use app\shop\model\ShopOrder;
use app\common\model\ShopMemberExpire;

class MemberInfo extends Controller
{
    public function index($id)
    {
        $memberExpire = ShopMember::where('uid',$id)->where('expire_time', '<=', time())->where('status','<>',2)->select();
        if(count($memberExpire)>0){
            foreach ($memberExpire as $item){
                ShopMember::where('id', $item['id'])->update(['status' => 2]);
            }
        }
        $memberNoExpire = ShopMember::where('uid',$id)->where('expire_time', '>', time())->where('status',2)->select();
        if(count($memberNoExpire)>0){
            foreach ($memberNoExpire as $item){
                ShopMember::where('id', $item['id'])->update(['status' => 1]);
            }
        }

        $grid = new Grid(new ShopMember);
        $grid->model()->where('uid',$id);
        $grid->card()->name('会员卡名称');
        $grid->status('状态')->using(Status::CARDSTATUS())->badge();
        $grid->total_num('可洗衣总次数');
//        $grid->use_num('已使用次数');
        $grid->residue_num('剩余次数');
//        $grid->free_num('每月免费次数');
//        $grid->free_use_num('已使用免费次数');
        $grid->bed_num('洗床品次数');
//        $grid->free_use_num('已使用床品次数');
        $grid->residue_bed_num('剩余洗床品次数');
        $grid->expire_card('到期时间');

        $grid->setFromOpen();
        $grid->hideExportButton();
        $grid->hideDeletesButton();

        //用户除了card_id意外的card
        $beyondCardId = ShopMember::beyondCardId($id);
        // 设置添加按钮参数
        $grid->setAddButtonParam(['UserId'=>$id,'beyondCardId'=>$beyondCardId]);
        // 设置编辑按钮参数
        $grid->setEditButtonParam(['UserId'=>$id],$beyondCardId);
        $grid->actions(function($action,$data){
//            halt($data);
            $action->hideDel();
            $action->hideEdit();
            $action->hideDetail();
            $button01 = new Button('续购',warm);
            $button01->save($data['id'], ['id' => $data['id'],'uid' => $data['uid'],'store_id'=>$data['store_id'],'total_num'=>$data['total_num'],'card_id'=>$data['card_id'],'expire_time'=>$data['expire_time']],'admin/member_info/addBuy','是否续购 '.$data['card']['name'].' ？');
            $action->append($button01);
            $button = new Button('编辑次数');
            $button->href(url('editCount') . "?id={$data['id']}", 'modal');
            $action->append($button);
        });
        return $grid->view();
    }

    //续购
    public  function addBuy(Request $request){
        $id = $request->param('id');
        $uid = $request->param('uid');
        $store_id = $request->param('store_id');
        $total_num = $request->param('total_num');
        $expire_time = $request->param('expire_time');
        $card_id = $request->param('card_id');
        $post =[
          'member_id'=>$id,
          'uid'=>$uid,
          'store_id'=>$store_id,
          'total_num'=>$total_num,
          'expire_time'=>$expire_time,
          'card_id'=>$card_id
        ];
        $this->addMemberFile($post);
        $this->success('续购成功','');
    }

    //添加
    public function form($UserId,$beyondCardId)
    {
        $store = session('store');
        $cards = ShopMemberCard::where('status',1)->where('is_deleted',0)->where('status',1)->where('is_deleted',0)->whereNotIn('id',$beyondCardId)->column('name','id');

        $form = new Form(new ShopMember);
        $form->select('card_id', '选择会员卡')->options($cards);
//        $form->text('coupon_price','优惠价格')->default(0);
        $form->hidden('uid','用户id')->default($UserId);
        $form->hidden('store_id','店铺id')->default($store['id']);

        $form->saving(function($post){

            $res = $this->addMemberFile($post);

            //会员卡信息数据
            $cardsInfo = ShopMemberCard::where('id',$post['card_id'])->find();
            $timestamp_plus_tiem = time() + $cardsInfo['effective_date'] * 24 * 60 * 60;
            $post['type'] = $cardsInfo['type'];
            $post['total_num'] = $cardsInfo['wash_number'];
            $post['expire_time'] = $timestamp_plus_tiem;
            $post['card_name'] = $cardsInfo['name'];
            $post['bed_num'] = $cardsInfo['bed_num'];
            (new ShopMember)->saveAll($post);
            return $post;
        });
        return $form->view();
    }
//    添加数据，
    public function addMemberFile($post){
        $userInfo = User::where('id',$post['uid'])->find();
        //会员卡信息数据
        $cardsInfo = ShopMemberCard::where('id',$post['card_id'])->find();

        //判断门店是否被禁用/下架
        $store = ShopStore::where('status',1)->find($post['store_id']);
        if (!$store) {
            return '该门店不存在或已下架';
        }
        //获取区域代理id
        $region_City = ShopSchoolRegion::where('id',$store['region_id'])->find();
        //生成订单号
        $order_sn = Data::uniqidDateCode();
        $goods_price = $cardsInfo['money'];
        //商品总价：商品结构+运费-优惠价
        $total_price = $goods_price - $post['coupon_price'];

        $orderData = [
            'title' => $cardsInfo['name'],
            'type' => 6,
            'uid' => $post['uid'],
            'city_id' => $region_City['pid'],
            'area_id' => $region_City['id'],
            'store_id' => $post['store_id']?$post['store_id']:0,
            'coupon_id' => $post['coupon_id']?$post['coupon_id']:0,
            'express_type' => 2,
            'order_no' => $order_sn,
            'discount_price' => $post['coupon_price'],//优惠价格
            'buy_num' => 1,
            'residue_num' =>  Token::laundryNum($post['store_id'])?Token::laundryNum($post['store_id']):0,
            'goods_price' => $goods_price,
            'total_price' => $total_price,
            'pay_type' => 2,
            'desc' => '',
            'is_discount' => 0,
            'discount' => 0,
            'name' => $userInfo['name'],
            'phone' => $userInfo['phone']
        ];

        $member_info = ShopMember::where('uid',$post['uid'])->where('type',$cardsInfo['type'])->find();
        if (time()>$member_info['expire_time']){
            $overdue_num = $member_info['total_num'] - $member_info['use_num'];
        }else{
            $overdue_num = 0;
        }
        $data = [
            'order_id' => $cardsInfo['id'],
            'overdue_num' => $overdue_num,
            'uid' => $post['uid']
        ];

        //续购，更新Member
        $is_member = ShopMember::where('id',$post['member_id'])->where('uid',$post['uid'])->find();
        if($is_member){
            //会员卡信息数据
            $updateMembercardsInfo = ShopMemberCard::where('id',$post['card_id'])->find();
            //判断会员卡是否过期
            if (time() >= $is_member['expire_time']){
                $update_plus_tiem = time() + $cardsInfo['effective_date'] * 24 * 60 * 60;
                $all_num = $updateMembercardsInfo['wash_number'];
                $use_num = 0;
                $bed_num = $updateMembercardsInfo['bed_num'];
                $bed_use_num = 0;
            }else{
                $update_plus_tiem = $is_member['expire_time'] + $cardsInfo['effective_date'] * 24 * 60 * 60;
                $all_num = $is_member['total_num'] + $updateMembercardsInfo['wash_number'];
                $use_num = $is_member['use_num'];
                $bed_num =$is_member['bed_num']  + $updateMembercardsInfo['bed_num'];
                $bed_use_num = $is_member['bed_use_num'];
            }

            $updateMemberArr = [
                'id'=>$post['member_id'],
                'total_num'=>$all_num,
                'use_num'=>$use_num,
                'bed_num'=>$bed_num,
                'bed_use_num'=>$bed_use_num,
                'expire_time'=>$update_plus_tiem
            ];
        }

        // 开启事务
        Db::startTrans();
        try {
            // 同时操作多个模型
            //操作shopOrder订单模型
            $shopOrderModel = new ShopOrder();
            $result1 = $shopOrderModel->insert($orderData);
            $order_id = $shopOrderModel->getLastInsID();
            Account::record($total_price, $post['uid'],"{$cardsInfo['name']}",1,0,"",$store['id'],$order_id);

            //操作shopMemberExpire订单模型
            $data = [
                'order_id' => $order_id,
                'overdue_num' => $overdue_num,
                'uid' => $post['uid']
            ];
            $result2 = (new ShopMemberExpire)->save($data);
            if($is_member){
                //续购
                //如果续购，更新shopMember
                $result3 = (new ShopMember)->update($updateMemberArr);
                // 如果任何一个操作失败，则抛出异常，事务将会回滚
                if (!$result1 || !$result2 || !$result3) {
                    throw new \Exception('操作失败');
                }
            }else{
                //添加
                // 如果任何一个操作失败，则抛出异常，事务将会回滚
                if (!$result1 || !$result2) {
                    throw new \Exception('操作失败');
                }
            }
            // 提交事务
            Db::commit();
            return $post;
        } catch (\Exception $e) {
            // 捕获异常，回滚事务
            Db::rollback();
            return $e->getMessage();
        }

    }

    //编辑次数
    public function editCount(){
        //$id = $this->request->param('id');
        $form = new Form(new ShopMember);
        $form->text('total_num','总次数');
        $form->text('use_num','已清洗次数');

        $form->saved(function($post,$model){
            file_put_contents('log_admin_change_user.txt', date('Y-m-d H:i:s').' '.json_encode($post,JSON_UNESCAPED_UNICODE) . "\r\n", FILE_APPEND | LOCK_EX);

            (new ShopMember)->saveAll($post);
            return $post;
        });
        return $form->view();
    }
}